﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RPSImporter.Infrastructure;
using System.Data;
using System.Configuration;
using System.IO;
using DB;
using RPSImporter.Services;
using RPSImporter.Models.Settings;

namespace RPSImporter.Models.Importers
{
   public class CSVImporter : IImporter
   {
      public IFile File { get; set; }
      public GeneralSettings Settings { get; set; }
      public string Error { get; set; }
      public IList<string> Messages { get; set; }

      public CSVImporter(IFile file)
      {
         this.File = file;
         this.Settings = new GeneralSettings();
         this.Messages = new List<string>();
      }

      public bool Import()
      {
         return this.Import(null);
      }

      public bool Import(string fileType)
      {
         this.Messages.Clear();
         try
         {
            string newFileName = this.File.FullName.Split('.')[0] + "_.csv";

            this.CreateSchemaFile(newFileName);
            string conStr = String.Format(ConfigurationManager.ConnectionStrings["csv"].ConnectionString);
            CsvDB.Instance.openDatabase(conStr);

            using (Stream stream = System.IO.File.Open(this.File.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
               using (Stream newStream = System.IO.File.Open(newFileName, FileMode.Create, FileAccess.ReadWrite))
               {
                  stream.CopyTo(newStream);
               }
            }

            DataTable dt = CsvDB.Instance.getDataTable("SELECT * FROM " + newFileName);
            System.IO.File.Delete(newFileName);

            var fileName = newFileName.Split('.')[0].Split('\\').Last();
            if (fileType != null)
            {
               Type type = Util.GetFileType(fileType);
               if (type != null)
               {
                  DatabaseSvc.Instance.Import(dt, type);
               }
            }
            else
            {
               if (fileName == this.Settings.CompanyFileName)
               {
                  DatabaseSvc.Instance.Import<Company>(dt);
               }
               else if (fileName == this.Settings.EnterpriseFileName)
               {
                  DatabaseSvc.Instance.Import<Enterprise>(dt);
               }
               else if (fileName == this.Settings.ExternalEnterprisesFileName)
               {
                  DatabaseSvc.Instance.Import<EnterpriseExt>(dt);
               }
               else if (fileName == this.Settings.HierarchyFileName)
               {
                  DatabaseSvc.Instance.Import<Hierarchy>(dt);
               }
               else if (fileName == this.Settings.PersonsFileName)
               {
                  DatabaseSvc.Instance.Import<Person>(dt);
               }
               else if (fileName == this.Settings.HoursPersonFileName)
               {
                  DatabaseSvc.Instance.Import<HoursPerson>(dt);
               }
               else if (fileName == this.Settings.HoursHierarchyFileName)
               {
                  DatabaseSvc.Instance.Import<HoursHierarchy>(dt);
               }
            }
            this.Messages = DatabaseSvc.Instance.Messages;
            return true;
         }
         catch (Exception ex)
         {
            this.Error = ex.Message;
            return false;
         }
         finally
         {
            CsvDB.Instance.Connection.Close();
         }
      }

      private void CreateSchemaFile(string fileName)
      {
         string _fileName = fileName.Split('\\').Last();
         string path = ConfigurationManager.AppSettings["ImportPath"];
         string delimiter = DatabaseSvc.Instance.Settings.GeneralSettings.FirstOrDefault().CsvDelimiter ?? "|";
         string schemaFile = path + "Schema.ini";

         using (Stream stream = System.IO.File.Open(schemaFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
         {
            using (StreamWriter writer = new StreamWriter(stream))
            {
               writer.WriteLine("[" + _fileName + "]");
               writer.WriteLine("Format=Delimited(" + delimiter + ")");
               writer.Flush();
            }
         }
      }
   }
}